import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

public class FirstRealm extends AuthorizingRealm {

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*
        * 业务上会根据name去查数据库获得权限,这里直接用list模拟权限
        * */
        String name= (String) principalCollection.getPrimaryPrincipal();
        List<String> permission=new ArrayList<String>();
        permission.add("user:add");
        permission.add("user:delete");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        for(String permissionString:permission){
            info.addStringPermission(permissionString);
        }
        return info;
    }

    /*
    * 自定义realm模拟登录
    * */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name= (String) authenticationToken.getPrincipal();
        if(!name.equals("zhang")){//模拟查询
            return null;
        }
        String password="123";//模拟查询
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(name,password,getName());
        return info;
    }
}
